package pers.jing.android.helper.page

import androidhelper.composeapp.generated.resources.Res
import androidhelper.composeapp.generated.resources.uninstall
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.Button
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel
import pers.jing.android.helper.model.PackageInfo
import pers.jing.android.helper.model.STATE_FAILURE
import pers.jing.android.helper.model.STATE_SUCCESS
import pers.jing.android.helper.widget.ConfirmDialog
import pers.jing.android.helper.widget.OutlinedFileField
import pers.jing.android.helper.widget.ProgressDialog

/**
 * 应用列表页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PkgListPage(viewModel: DeviceViewModel = koinViewModel<DeviceViewModel>()) {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val uiProgress = viewModel.uiProgress.collectAsState()
        val uiResult = viewModel.uiResult.collectAsState()

        var apkPath by remember {
            mutableStateOf("")
        }

        var okEnabled by  remember {
            mutableStateOf(false)
        }

        Row(
            modifier = Modifier.fillMaxWidth()
                .padding(horizontal = 16.dp)
                .padding(top = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedFileField(
                title = "选择APK",
                filePath = apkPath,
                ext = ".apk",
                modifier = Modifier.weight(1.0f)) {
                apkPath = it
                okEnabled = checkOkEnabled(it)
            }

            Button(
                modifier = Modifier.padding(start = 16.dp),
                onClick = {
                    viewModel.install(apkPath)
                },
                enabled = okEnabled
            ) {
                Text(
                    text = "安装应用"
                )
            }
        }
        //搜索
        var searchText = viewModel.searchText.collectAsState()
        OutlinedTextField(
            value = searchText.value,
            onValueChange = {
                viewModel.search(it)
            },
            modifier = Modifier.fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 10.dp)
        )

        val pkgList = viewModel.showPkgList.collectAsState()
        PkgListItemWidget(pkgList.value,
            modifier = Modifier.fillMaxWidth()
                .weight(1.0f)
                .padding(horizontal = 16.dp),
            onDeleteData = { item ->
                viewModel.deletePkgData(item)
            },
            onUninstall = { item ->
                viewModel.uninstallPkg(item)
            }
        )

        if (uiProgress.value.show) {
            ProgressDialog("正在安装...")
        }
        if (STATE_SUCCESS == uiResult.value.state || STATE_FAILURE == uiResult.value.state) {
            ConfirmDialog(
                msg = uiResult.value.msg?:"未知错误",
                onConfirm = {
                    viewModel.clearUIResult()
                }
            ) {
                viewModel.clearUIResult()
            }
        }
    }
}


/**
 * 检查OK按钮是否可以点击
 */
fun checkOkEnabled(apkPath: String): Boolean {
    if (apkPath.isEmpty() || apkPath.isBlank()) {
        return false
    }
    return true
}

@Composable
fun PkgListItemWidget(pkgList: List<PackageInfo>, modifier: Modifier,
                      onDeleteData: (PackageInfo) -> Unit,
                      onUninstall: (PackageInfo) -> Unit) {
    LazyColumn(
        modifier = modifier
    ) {
        itemsIndexed(pkgList) { index, item ->
            ElevatedCard(
                modifier = Modifier.padding(bottom = 10.dp)
            ) {
                Column{
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 10.dp)
                            .padding(horizontal = 16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = "应用包名: ${item.pkgName}"
                        )
                        val appType = if (item.system) {
                            "预装"
                        } else {
                            "三方"
                        }
                        Text(
                            text = "应用类型: $appType"
                        )
                    }
                    HorizontalDivider(
                        modifier = Modifier.fillMaxWidth().padding(top = 10.dp)
                    )
                    Row(
                        horizontalArrangement = Arrangement.SpaceAround,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        //删除数据
                        TextButton(
                            onClick = {
                                onDeleteData(item)
                            }
                        ) {
                            Text(
                                text = "删除数据"
                            )
                        }

                        //卸载
                        TextButton(
                            onClick = {
                                //卸载应用
                                onUninstall(item)
                            },
                            enabled = !item.system
                        ) {
                            Text(
                                text = stringResource(Res.string.uninstall)
                            )
                        }
                    }
                }

            }
        }
    }
}